#include "importhomes.h"




ImportHomes::ImportHomes( DB_Manager * dbin , int tipo , QObject * parent )
	: QObject( parent )
{
	  tipocasa = tipo;
	  setObjectName(QString::fromUtf8("ImportHomes"));
	  passaggi = 0;
	  desiderio = 0;
	  successi = 0;
	  SessionCall = 0;
	  Continuergo = true;
	  SessionRunnging = false;
	  db = dbin;
	  ConnectionDB = db->isValid();
	  qDebug() << "### connecter -> " << ConnectionDB;
}


void ImportHomes::GetEurorate()
{
	QString invia = "PD94bWwgdmVyc2lvbj0nMS4wJyBlbmNvZGluZz0nVVRGLTgnIHN0YW5kYWxvbmU9J25vJz8+CjxTT0FQLUVOVjpFbnZlbG9wZSB4bWxuczpTT0FQLUVOVj0iaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvc29hcC9lbnZlbG9wZS8iIHhtbG5zOnhzaT0iaHR0cDovL3d3dy53My5vcmcvMjAwMS9YTUxTY2hlbWEtaW5zdGFuY2UiIHhtbG5zOnNvYXA9Imh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzZGwvc29hcC8iIHhtbG5zOnRucz0iaHR0cDovL3dzLnRpY2luby10b3VyaXNtLmNoL3dzZGwiIHhtbG5zOnhzZD0iaHR0cDovL3d3dy53My5vcmcvMjAwMS9YTUxTY2hlbWEiID4KICAgICA8U09BUC1FTlY6Qm9keT4KICAgICAgICAgIDxtbnMxOmdldEV1cm9FeGNoYW5nZVJhdGUgeG1sbnM6bW5zMT0iaHR0cDovL3dzLnRpY2luby10b3VyaXNtLmNoL3dzZGwiIC8+CiAgICAgPC9TT0FQLUVOVjpCb2R5Pgo8L1NPQVAtRU5WOkVudmVsb3BlPg==";
	
	QString Stream = fromBase64(invia);
	QDomDocument euro_doc;
	   QString errorStr;
     int errorLine, errorColumn, position;
	   if (!euro_doc.setContent(Stream,false, &errorStr, &errorLine, &errorColumn)) {
		  emit EndProcessing();
			return;
     }
	LoadSoa *dammieuro = new LoadSoa(15,QUrl("http://ws.ticino.ch/systemManager?wsdl"),euro_doc);
	connect(dammieuro, SIGNAL(take(int,int)), this, SLOT(Euroarriva(int,int)));
	dammieuro->Start();
}

void ImportHomes::Euroarriva(int numero ,int numhttp )
{
		LoadSoa *ht = qobject_cast<LoadSoa *>(sender());
		QDomDocument doc_entra = ht->HDoc();
		QDomElement root = doc_entra.documentElement();
	  QDomElement d1 = root.firstChildElement("S:Body");
	  QDomElement d2 = d1.firstChildElement("ns2:getEuroExchangeRateResponse");
	  QDomElement r = d2.firstChildElement("return");
    double quantifruneuro = r.firstChildElement("rate").text().toDouble();
	  double fattoremoltipl = 1.000000000000 / quantifruneuro;
	  setter.setValue("valuta/dayEURO",quantifruneuro); 
	  setter.setValue("valuta/dayCHF",fattoremoltipl); 
	  QDate aggiornatoil = DateFromUtc( r.firstChildElement("date").text() );
	  setter.setValue("valuta/Update",aggiornatoil); 
	  ///////////qDebug() << "### Euroarriva -> " << aggiornatoil;
	  QString messaggio =  QString("Un euro = CHF %1 \nUn franco = euro %2 ").arg(quantifruneuro, 0, 'f', 8).arg(fattoremoltipl, 0, 'f', 8);
	  QMessageBox::information(0, tr("Aggiornato il cambio con sucesso il %1.").arg(aggiornatoil.toString()),messaggio);
	   ////////qDebug() << "### Euroarriva -> " << fattoremoltipl;
	   /////////qDebug() << "### Euroarriva -> " << doc_entra.toString(1);
	   emit EndProcessing();
}



void ImportHomes::StartCaseGet()
{
	desiderio = 4;
	
	      db->GrepOrfani();
			  soa = new SoaRequest(this);
			  connect(soa, SIGNAL(SessionStatus(bool)), this, SLOT(SessionGlobal(bool)));
			  connect(soa, SIGNAL(SendError()), this, SLOT(ErrorFound()));
	      connect(soa, SIGNAL(LastDone(int)), this, SLOT(Job(int)));
			  soa->Login();
}



void ImportHomes::SessionGlobal( bool e )
{
	const int idnostro = db->IdTipo(tipocasa);
	
	SessionRunnging = e;
	SessionCall++;
	qDebug() << "### SessionGlobalRunning-> " << SessionRunnging;
	if (SessionRunnging) {
		qDebug() << "### SessionGlobalRunning->Runn Job...... ";
		emit play(QString("Sessione start ok..."));
		if (desiderio == 4) {
			emit play(QString("Richiesta del tipo %1 = %2").arg(tipocasa).arg(db->TipoNome(idnostro)));
		soa->ListaCase(tipocasa);
		} else if (desiderio == 0) {
			qDebug() << "### SessionGlobalRunning-> " << desiderio;
			GLogout();
		} else {
			GLogout();
		}
	} else {
		
		
		qDebug() << "### SessionGlobalRunning->Runn close all Job...... ";
		emit play(QString("Sessione chiusa ... %1 jobs ok ... tipo %2 = %3").arg(successi).arg(tipocasa).arg(db->TipoNome(idnostro)));
		////////emit LastSessionClose();
		QApplication::restoreOverrideCursor();
		//////QMessageBox::information(0, tr("Remote session"),tr("La sessione remota e stata chiusa con successo."));
	}
	if (!e) {
	
	}
	
}

void ImportHomes::Job( const int jobnummer )
{
	 qDebug() << "### Job(" << jobnummer << ") -> " << passaggi;
	 if (jobnummer == 11)  {
	 qDebug() << "### case entra " << jobnummer;
	 MultiRequestStart(soa->Doc_Current());   ///// QDomDocument Doc_Current()
		 ///////LeggiSoloUno(20649);
	 } else {
		GLogout();
	 }
}

void ImportHomes::ImageAttributeGet()
{

	for (int o = 999;o  < 1100; ++o)  {
		LaunchGetImage(o);
	}
	
	/*
					for (int i = 0;i  < 59; ++i)  {
							 ////const int nummeratt = i + 1000;
						    LaunchGetImage(i + 1000);
						    LaunchGetImage(i + 2000);
								LaunchGetImage(i + 2100);
						    LaunchGetImage(i + 2200);
					}
	*/
	
}

void ImportHomes::LaunchGetImage(const int nr )
{
	const QString item = QString("http://ticino.ch/immagini/icone_caratteristiche/attribute_%1.gif").arg(nr);
	RequestStreams *httpgetter = new RequestStreams();
	httpgetter->Setting(this,nr,QUrl(item),STREAM_GIF);
	httpgetter->start(QThread::LowPriority);
	
}



void ImportHomes::stream_in(const int nr )
{
	  return;
	  //////qDebug() << "### stream_in(" << nr << ") -> ";
	  QString listfile = QDir::currentPath() + QString("/attriNN/att_%1.png").arg(nr);
	  LoadGet *ht = qobject_cast<LoadGet *>(sender());
			qDebug() << "### cast ok" << nr;
			Dircheck(QDir::currentPath() + QString("/attriNN/"));
			QPixmap inc = ht->pics();
			inc.save (listfile,"PNG");
}




void ImportHomes::LeggiSoloUno( const int numert )
{
	  pending.clear();
	  entrati.clear();
	
									    QDomDocument doc = soa->Casa_Doc(numert);
									    if (doc.toString(5).size() > 0) {
													qDebug() << "### iditem " << numert;
													QString requestFile = QDir::currentPath() +"/request/res_"+QString("%1.xml").arg(numert);
													fwriteutf8(requestFile,doc.toString(5));
												   /* start multi request QThread */
												   RequestSoa *grephttp = new RequestSoa();
							              grephttp->Setting(this,numert,_URLHOUSES_,doc); 
							              grephttp->start(QThread::LowPriority);
							               pending.insert(numert,grephttp);
											}
											
					if (pending.size() < 1) {
						GLogout();
					return;
					}
	Summreciver = pending.size();
	Contatore = 0;
					
					
					
	progress = new QProgressDialog(0,Qt::Dialog);
  progress->setMinimumWidth (400);
	progress->setLabelText (tr("In attesa di %1 Richieste...").arg(Summreciver));
  progress->setMinimumDuration (1200);
  progress->setCancelButtonText (tr("Stop & blocca sessione..."));
	progress->setMaximum(Summreciver);
	connect(progress, SIGNAL(canceled()), this, SLOT(ExitChainer()));
	
}


bool ImportHomes::Permission( const int id )
{
	if (id == 0) {
		return false;   ///////  casa di prova = 84629
	}
	return true;
}

/* leggi la lista in entrata */
void ImportHomes::MultiRequestStart( QDomDocument stream )
{
	  int misura = 0;
		pending.clear();
	  entrati.clear();
	  if (stream.toString(5).size() > 10) {
			
		QString listfile = WORK_TICINO_SESSION +"_UltimaLista.xml";
		fwriteutf8(listfile,stream.toString(5));
			
			
			 GrepTicinoHousesObjekt xml_loader;
	                          xml_loader.Indexing(stream.toString(5),5);
			 QMap<int,QString> iplist = xml_loader.CityNames();
			   QMapIterator <int,QString> d(iplist);
                while (d.hasNext()) {
                      d.next();
									    const int iditem = d.key();
									    QDomDocument doc = soa->Casa_Doc(iditem);
									    if (doc.toString(5).size() > 0 && Permission(iditem)) {
													qDebug() << "### iditem " << iditem << "|" << d.value();
													//////QString requestFile = QDir::currentPath() +"/request/res_"+QString("%1.xml").arg(iditem);
													//////fwriteutf8(requestFile,doc.toString(5));
												   /* start multi request QThread */
												   RequestSoa *grephttp = new RequestSoa();
							              grephttp->Setting(this,iditem,_URLHOUSES_,doc); 
							              grephttp->start(QThread::LowPriority);
							               pending.insert(iditem,grephttp);
									     
							            
														misura++;
											}
                }
			
								
								if (misura < 1) {
									GLogout();
			            return;
								}
			
		} else {
			GLogout();
			return;
		}
		
	Summreciver = pending.size();
	Contatore = 0;
		QApplication::restoreOverrideCursor();
	progress = new QProgressDialog(0,Qt::Dialog);
  progress->setMinimumWidth (400);
	progress->setLabelText (tr("In attesa di %1 Richieste del tipo %2").arg(Summreciver).arg(tipocasa));
  progress->setMinimumDuration (1200);
  progress->setCancelButtonText (tr("Stop & blocca sessione..."));
	progress->setMaximum(Summreciver);
	connect(progress, SIGNAL(canceled()), this, SLOT(ExitChainer()));
}

void ImportHomes::ExitChainer()
{
	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
	
	Continuergo = false;
	GLogout();
	   delete progress;
	   progress = 0;
		 pending.clear();
	
}


void ImportHomes::GLogout()
{
	qDebug() << "### GLogout-> #########################################################" << passaggi;
	qDebug() << "### GLogout-> #########################################################" << passaggi;
	QTimer::singleShot(50, this, SLOT(Exit()));  
}

void ImportHomes::Exit()
{
	qDebug() << "### log out call Exit-> " << passaggi;
	soa->Logout();
}



/* leggi le singole case */
void ImportHomes::ProcessingInList()
{
	/* make logout !!!! */
	
	if (!Continuergo) {
		GLogout();
		return;
	}
	GLogout();
	
	qDebug() << "############### ProcessingInList  start  #######################";
	Contatore = 0;
	qApp->processEvents();
	progress->setMaximum(entrati.size());
	successi = 0;
	int calendari = 0;
	imagepics.clear();
	
	  QMapIterator <int,QDomDocument> d(entrati);
	
                 while (d.hasNext()) {
                       d.next();
									     Contatore++;
									     QMap<int,DayCell> dayocc;
									     dayocc.clear();
									     QDomDocument doc = d.value();
									     const int numero = d.key();
									     GrepTicinoHousesObjekt xmlParse;
									     QDateTime timer1( QDateTime::currentDateTime() ); 
                                         fwriteutf8(WORK_TICINO_SESSION + "request_item_" +timer1.toString ("d_M_yy_h.m.s.zzz")+".txt",doc.toString(5));
									     
									     bool contienes = db->HavingIDOggetto(numero);
		                                 bool Go_In_OK = xmlParse.Load(doc.toString(5),numero,1);
									     const int CityTiTurismoId = xmlParse.ti_c_id();
									     QStringList imagefromids =  xmlParse.picimage();
                                          if (!contienes) {
                                              db->NuovoOggettoID(numero,timer1.toTime_t());
                                          }
									     int iddelpaese = db->IdPaese(CityTiTurismoId);
									     qDebug() << "### Go_In_OK " << d.key() << "-" << Go_In_OK << contienes << "-id-" << numero;
									     if (Go_In_OK && Continuergo) {
												     bool goupdates = db->UpdatesOggetti(iddelpaese,numero,xmlParse.FieldValue(),tipocasa);
												     if (goupdates) {
															 /* make calendar */
															 successi++;
															 qDebug() << "### goupdates-----> " << goupdates;
															 if (imagefromids.size() > 0) {
															 imagepics.insert(numero,imagefromids);
															 }
															 dayocc = xmlParse.CalValue();
															 if (dayocc.size() > 0) {
																 calendari++;
																 
																 qDebug() << "### calendari " << calendari;
																 qDebug() << "### numero " << numero;
																 
                                                TableCalendar ncali;
                                                ncali.appendlist(dayocc);
                                               ncali.owner = numero; 
                                               /////ncali.Html_build();		
                                               QString resave1 = saveCalendar(ncali);		
                                               db->Save_Calendar(numero,resave1,"");	
																 
																 qDebug() << "### inserisci calendari tipocasa->" << tipocasa;
																 
																  /*
																  QString dat = db->Get_Calendar(numero);
																       if (dat.size() > 0) {
																				        TableCalendar cali = openCalendar(dat);
																				        cali.appendlist(dayocc); 
																				        cali.Html_build();
																				        QString resave = saveCalendar(cali);
																								db->Save_Calendar(numero,resave,encodeBase64(cali.web));	
																			 } else {
																				       TableCalendar ncali;
																							 ncali.appendlist(dayocc);
                                               ncali.owner = numero; 
                                               ncali.Html_build();		
                                               QString resave1 = saveCalendar(ncali);		
                                               db->Save_Calendar(numero,resave1,encodeBase64(ncali.web));																			 
																				 
																			 }
																 */
															 }
															 
														 }
												 
											 }
									     progress->setValue(Contatore);
	                                    qApp->processEvents();
											 //////////std::cout <<  "# Read " << Contatore << " from " << entrati.size() << "cal " << dayocc.size() << "\r";
	                      //////////////std::fflush ( stdin );
									      /////////////pending.clear();
									      xmlParse = 0;
								 }
	
	   //////////////qDebug() << "####Cal->" << calendari << "########### ProcessingInList  end  summ OK. " << successi << " #######################";
	   progress->deleteLater();
	   progress = 0;
		 pending.clear();
								 
qDebug() << "### ende processing ##########################################################################?";
								 
					 ////////////QMapIterator <int,QStringList> i(imagepics);
                ////////while (i.hasNext()) {
                     ////////  i.next();
									     /////////qDebug() << "## " << i.key() << " images " << i.value().join(",") << " ##";
                //////////}			 
			db->GrepOrfani();
			////////GLogout();
			emit EndProcessing();
		 
}



void ImportHomes::childFinished( int hid , int nr )
{
	if (!Continuergo) {
		return;
	}
	

	
	
	Contatore++;
	std::cout <<  "# Read " << Contatore << " from " << pending.size() << "\r";
	std::fflush ( stdin );
	if (Contatore < pending.size() - 4) {
	qApp->processEvents();
	progress->setValue(Contatore);
		QApplication::restoreOverrideCursor();
	}
	///////qDebug() << "######################################";
	///////QString fix = QDir::currentPath() +"/tmp/AAAA_res_"+QString("%1.xml").arg(hid);
	//////QString fix1 = QDir::currentPath() +"/tmp/BBBBres_"+QString("%1.xml").arg(hid);
	LoadSoa *ht = qobject_cast<LoadSoa *>(sender());
	QDomDocument doc_entra = ht->HDoc();
	/////////qDebug() << "### prendi -> " << prendi;
	//////////qDebug() << "### Htpp_id " << ht->Htpp_id() << "-" << hid;
	//////////qDebug() << "### id " << ht->Get_id();
	if (doc_entra.toString(5).size() > 0) {
	//////fwriteutf8(fix,doc_entra.toString(5));
	///////////fwriteutf8(fix1,ht->Doc().toString(3)); 
	entrati.insert(hid,doc_entra);
	qApp->processEvents();
	} else {
	Summreciver--;
	}
	ht->abort();
	ht->deleteLater();
	
	if (entrati.size() >= Summreciver) {
		qDebug() << "############### end processing QThread #######################";
		qDebug() << "### entrati -> " << entrati.size();
		qDebug() << "### pending -> " << pending.size();
		Contatore = 0;
		/////////////delete progress;
		/////////progress = 0;
		 //////progress = new QProgressDialog(0,Qt::Popup);
		 progress->setLabelText (tr("Trasformazione di %1 documenti...").arg(entrati.size()));
		 progress->setMaximum(entrati.size());
		 progress->setValue(entrati.size() - 5 );
		 connect(progress, SIGNAL(canceled()), this, SLOT(ExitChainer()));
	   ///////progress->setLabelText (tr("Trasformazione di %1 documenti...").arg(entrati.size()));
		 QTimer::singleShot(1, this, SLOT(ProcessingInList()));  
		 
		return;
	}
	///////qDebug() << "### childFinished -> Htpp_id sender  " << hid << "-" << nr;
	/////////qDebug() << "### entrati -> " << entrati.size();
	///////////qDebug() << "### pending -> " << pending.size();
	////////qDebug() << "######################################";
	
}





void ImportHomes::ErrorFound()
{
	qDebug() << "### !!!!!ErrorFound -> " << soa->lastid() << " ###############################";
	
	QApplication::restoreOverrideCursor();
	QApplication::restoreOverrideCursor();
	QMessageBox::information(0, tr("Remote session"),tr("La sessione dal server remoto non figura valida! ultimo id %1.").arg(soa->lastid()));
	
	
}










